package org.Menu;

import org.File.FileOperate;
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileView;

public class Menu extends JFrame{
	private TestAction saveAction;
	private TestAction saveAsAction;
	private JCheckBoxMenuItem readonlyItem;
	private JPopupMenu popup;
	private JTextArea textArea;
	private JScrollPane scrollPane;
	private JFileChooser chooser;
	private JLabel label;
	private String title;
	private PasswordChooser dialog=null;
	
	public Menu()
	{
		title="New File";
		setTitle(title);
		setSize(500,300);
		
		JMenu fileMenu=new JMenu("File");
		JMenuItem newItem=fileMenu.add(new TestAction("New"));
		
		JMenuItem openItem=fileMenu.add(new TestAction("Open"));
		openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));
		fileMenu.addSeparator();
		openItem.addActionListener(new FileOpenListener());
		
		saveAction=new TestAction("Save");
		JMenuItem saveItem=fileMenu.add(saveAction);
		saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));
		
		saveAsAction=new TestAction("Save As");
		JMenuItem saveAsItem=fileMenu.add(saveAsAction);
		fileMenu.addSeparator();
		
		JMenuItem conn=new JMenuItem("Connection");
		conn.addActionListener(new connection());
		fileMenu.add(conn);

		fileMenu.add(new AbstractAction("Exit")
		{

			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				System.exit(0);
			}
		}
				);
		
		readonlyItem=new JCheckBoxMenuItem("Read-Only");
		readonlyItem.addActionListener(new ActionListener()
		{

			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				boolean saveOK=!readonlyItem.isSelected();
				saveAction.setEnabled(saveOK);
				saveAsAction.setEnabled(saveOK);
				
			}
			
		});
		
		ButtonGroup group=new ButtonGroup();
		
		JRadioButtonMenuItem insertItem=new JRadioButtonMenuItem("Insert");
		insertItem.setSelected(true);
		JRadioButtonMenuItem overtypeItem=new JRadioButtonMenuItem("OverType");
		
		group.add(insertItem);
		group.add(overtypeItem);
		
		TestAction cutAction=new TestAction("Cut");
		//cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif"));
		TestAction copyAction=new TestAction("Copy");
		TestAction pasteAction=new TestAction("Paste");
		
		JMenu editMenu=new JMenu("Edit");
		editMenu.add(cutAction);
		editMenu.add(copyAction);
		editMenu.add(pasteAction);
		
		TestAction wrapAction=new TestAction("Wrap");
		
		JMenu formMenu=new JMenu("Form");
		formMenu.add(wrapAction);
		
		JMenu optionMenu=new JMenu("Options");
		
		optionMenu.add(readonlyItem);
		optionMenu.addSeparator();
		optionMenu.add(insertItem);
		optionMenu.add(overtypeItem);
		
		editMenu.addSeparator();
		editMenu.add(optionMenu);
		
		JMenu helpMenu=new JMenu("Help");
		helpMenu.setMnemonic('H');
		
		JMenuItem indexItem=new JMenuItem("Index");
		indexItem.setMnemonic('I');
		helpMenu.add(indexItem);
		
		TestAction aboutAction=new TestAction("About");
		aboutAction.putValue(TestAction.SHORT_DESCRIPTION, "You can know someThing");
		helpMenu.add(aboutAction);
		
		JMenuBar menuBar=new JMenuBar();
		setJMenuBar(menuBar);
		
		menuBar.add(fileMenu);
		menuBar.add(editMenu);
		menuBar.add(formMenu);
		menuBar.add(helpMenu);
		
		popup=new JPopupMenu();
		popup.add(cutAction);
		popup.add(copyAction);
		popup.add(pasteAction);
		
		JPanel panel=new JPanel();
		panel.setComponentPopupMenu(popup);
		add(panel);
		
		panel.addMouseListener(new MouseAdapter(){});
		
		textArea=new JTextArea(4,20);
		scrollPane=new JScrollPane(textArea);
		
		add(scrollPane,BorderLayout.CENTER);
		
		/*文件选择框*/
		//label=new JLabel();
		//add(label);
		
		chooser=new JFileChooser();
		final ExtensionFileFilter filter=new ExtensionFileFilter();
		filter.addExtension("txt");
		filter.addExtension("doc");
		filter.addExtension("docx");
		filter.setDescription("word files");
		chooser.setFileFilter(filter);
		chooser.setAccessory(new ImagePreviewer(chooser));
		chooser.setFileView(new FileIconView(filter,new ImageIcon("palette.gif")));

	}
	
	private class connection implements ActionListener
	{

		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			if(dialog==null)
				dialog=new PasswordChooser();
			dialog.setUser(new User("YourName",null));
			
			if(dialog.showDialog(Menu.this, "Connect"));
			{
				User u=dialog.getUser();
				textArea.append("UserName:"+u.getName()+"  Password:"+(new String(u.getPassword())));
			}
		}
		
	}
	
	private class FileOpenListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			chooser.setCurrentDirectory(new File("."));
			int result =chooser.showOpenDialog(Menu.this);
			if(result==JFileChooser.APPROVE_OPTION)
			{
				textArea.setText("");
				String name=chooser.getSelectedFile().getName();
				title=name;
				setTitle(title);
				File selFile=chooser.getSelectedFile();
				try {
					BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(selFile),"gbk"));
					String line=null;
					while ((line=reader.readLine())!=null) 
					{
						textArea.append(line+"\n");
						Thread.sleep(30);//线程暂停,以看到读取过程效果
					}
					} catch (Exception e1) {
				    e1.printStackTrace();
				   }
				   JOptionPane.showMessageDialog(textArea, "Read Finish");
			}
			
		}
	}
	
	private	class TestAction extends AbstractAction{
		final Logger logger = LoggerFactory.getLogger(TestAction.class);
		Clipboard clipboard=getToolkit().getSystemClipboard();
		public TestAction(String name) {
			// TODO Auto-generated constructor stub
			super(name);
		}
		public void actionPerformed(ActionEvent e)
		{
			if((String) getValue(TestAction.NAME)=="New")
			{
				title="New File";
				setTitle(title);
				textArea.setText("");
				//validate();
			}
			
			if((String) getValue(TestAction.NAME)=="Save")
			{
				/*to be continue*/
				//SaveTextFile save=new SaveTextFile(,"qq");
				FileOperate saveOperator=new FileOperate();
				
				String str=new String();
				str=textArea.getText();
				Pattern pattern = Pattern.compile(".Java$.*");
				Matcher matcher = pattern.matcher(title);
				if(matcher.matches())
					saveOperator.newFile(title, str);
				else
					saveOperator.newFile(title+".txt", str);

				/*String str=new String();
				str=textArea.getText();
				File f=new File("");
				SaveTextFile saveFile=new SaveTextFile(title,str);
				saveFile.writeToFile();*/
				
			}
			
			if((String) getValue(TestAction.NAME)=="Save As")
			{
				chooser.setCurrentDirectory(new File("."));
				int result =chooser.showOpenDialog(Menu.this);
				if(result==JFileChooser.APPROVE_OPTION)
				{
					String name=chooser.getSelectedFile().getName();
					title=name;
					setTitle(title);
					//label.setIcon(new ImageIcon(name));
					
					FileOperate saveAsOperator=new FileOperate();
					
					String str=new String();
					str=textArea.getText();
					
					File file=new File(name);
					if(chooser.accept(file))
						saveAsOperator.newFile(name, str);
					else
						saveAsOperator.newFile(name+".txt", str);
				}
			}
			if((String) getValue(TestAction.NAME)=="Cut")
			{
				String temp=textArea.getSelectedText();       //拖动鼠标选取文本。   
                StringSelection text=new StringSelection(temp);   
                clipboard.setContents(text,null);   
                int start=textArea.getSelectionStart();   
                int end=textArea.getSelectionEnd();     
                textArea.replaceRange("",start,end)   ;
				
			}
			if((String) getValue(TestAction.NAME)=="Copy")
			{
				String temp=textArea.getSelectedText();     //拖动鼠标选取文本。   
                StringSelection text=new   StringSelection(temp);   
                clipboard.setContents(text,null);
			}
			if((String) getValue(TestAction.NAME)=="Paste")
			{
				 Transferable contents=clipboard.getContents(this);   
                 DataFlavor flavor=   DataFlavor.stringFlavor;   
                 if(
                		 contents.isDataFlavorSupported(flavor))   
                	 	try{
                	 		String str;   
                	 		str=(String)contents.getTransferData(flavor);   
                	 		textArea.append(str);   
                           }   
                 		catch(Exception   ee)
                 		{}   
			}
			if((String) getValue(TestAction.NAME)=="Wrap")
			{
				boolean wrap=!textArea.getLineWrap();
				textArea.setLineWrap(wrap);
				scrollPane.revalidate();
			}
			logger.info("{}selected",getValue(TestAction.NAME));
		}
		
	}
}


/*对话框*/
class PasswordChooser extends JPanel
{
	private JTextField username;
	private JPasswordField password;
	private JButton okBtn;
	private boolean ok;
	private JDialog dialog;
	public PasswordChooser()
	{
		setLayout(new BorderLayout());
		
		JPanel panel=new JPanel();
		panel.setLayout(new GridLayout(2,2));
		panel.add(new JLabel("User Name"));
		panel.add(username=new JTextField(""));
		panel.add(new JLabel("Password"));
		panel.add(password=new JPasswordField(""));
		
		add(panel,BorderLayout.CENTER);
		
		okBtn=new JButton("OK");
		okBtn.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				ok=true;
				dialog.setVisible(false);
			}
		});
		
		JButton canBtn=new JButton("Cancel");
		canBtn.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				//ok=true;
				dialog.setVisible(false);
			}
		});
		
		JPanel buttonPanel=new JPanel();
		buttonPanel.add(okBtn);
		buttonPanel.add(canBtn);
		add(buttonPanel,BorderLayout.SOUTH);
	}
	
	public void setUser(User u)
	{
		username.setText(u.getName());
	}
	
	public User getUser()
	{
		return new User(username.getText(),password.getPassword());
	}
	
	public boolean showDialog(Component parent,String title)
	{
		ok=false;
		
		Frame owner=null;
		if(parent instanceof Frame)
			owner=(Frame)parent;
		else 
			owner=(Frame)SwingUtilities.getAncestorOfClass(Frame.class, parent);
		if(dialog==null || dialog.getOwner()!=owner)
		{
			dialog=new JDialog(owner,true);
			dialog.add(this);
			dialog.getRootPane().setDefaultButton(okBtn);
			dialog.pack();
		}
		dialog.setTitle(title);
		dialog.setVisible(true);
		return ok;
	}
}

class User
{
	private String name;
	private char[] password;
	public User(String aName,char[]apassword)
	{
		name=aName;
		password=apassword;
	}
	public String getName()
	{
		return name;
	}
	public char[] getPassword()
	{
		return password;
	}
	public void setName(String aName)
	{
		name=aName;
	}
	public void setPassword(char[]aPassword)
	{
		password=aPassword;
	}
}


/*文件选择对话框*/
class ExtensionFileFilter extends FileFilter
{
	private String description=".";
	private ArrayList<String> extensions=new ArrayList<String>();
	@Override
	public boolean accept(File f) {
		// TODO Auto-generated method stub
		if(f.isDirectory())
			return true;
		String name=f.getName().toLowerCase();
		
		for(String extension:extensions)
			if(name.endsWith(extension))
				return true;
		return false;
	}

	public void addExtension(String extension)
	{
		if(!extension.startsWith("."))
			extension='.'+extension;
		extensions.add(extension.toLowerCase());
	}
	
	public void setDescription(String aDescription)
	{
		description=aDescription;
	}
	
	public String getDescription()
	{
		return description;
	}
	
}

class FileIconView extends FileView
{
	private FileFilter filter;
	private Icon icon;
	public FileIconView(FileFilter aFilter,Icon anIcon)
	{
		filter=aFilter;
		icon=anIcon;
	}
	public Icon getIcon(File f)
	{
		if(!f.isDirectory() && filter.accept(f))
			return icon;
		else 
			return null;
	}
}

class ImagePreviewer extends JLabel
{
	public ImagePreviewer(JFileChooser chooser)
	{
		setPreferredSize(new Dimension(100,100));
		setBorder(BorderFactory.createEtchedBorder());
		chooser.addPropertyChangeListener(new PropertyChangeListener() 
		{
			public void propertyChange(PropertyChangeEvent e)
			{
				if(e.getPropertyName()==JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
				{
					File f=(File)e.getNewValue();
					if(f==null)
					{
						setIcon(null);
						return;
					}
					ImageIcon icon=new ImageIcon(f.getPath());
					if(icon.getIconWidth()>getWidth())
						icon=new ImageIcon(icon.getImage().getScaledInstance(getWidth(), -1, Image.SCALE_DEFAULT));
					setIcon(icon);
				}
			}
		});
	}
}